<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="login-bg">
      <div class="bg-circle bg-circle-1"></div>
      <div class="bg-circle bg-circle-2"></div>
      <div class="bg-circle bg-circle-3"></div>
    </div>

    <!-- 登录卡片 -->
    <div class="login-card">
      <!-- 系统标题 -->
      <div class="login-header">
        <div class="logo-container">
          <el-icon class="logo-icon" size="48">
            <ShoppingCart/>
          </el-icon>
        </div>
        <h1 class="system-title">收银管理系统</h1>
        <p class="system-subtitle">POS System</p>
      </div>

      <!-- 登录表单 -->
      <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          @keyup.enter="handleLogin"
      >
        <!-- 用户名输入 -->
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              size="large"
              :prefix-icon="User"
              clearable
          />
        </el-form-item>

        <!-- 密码输入 -->
        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              :prefix-icon="Lock"
              show-password
              clearable
          />
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item prop="captcha" v-if="loginSettings.enableCaptcha">
          <div class="captcha-container">
            <el-input
                v-model="loginForm.captcha"
                :placeholder="`请输入${loginSettings.captchaLength}位验证码`"
                size="large"
                :prefix-icon="Key"
                clearable
                style="flex: 1; margin-right: 12px;"
            />
            <div class="captcha-image" @click="refreshCaptcha">
              <img :src="captchaUrl" alt="验证码"/>
            </div>
          </div>
        </el-form-item>

        <!-- 记住密码 -->
        <el-form-item>
          <div class="login-options">
            <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button
              type="primary"
              size="large"
              class="login-btn"
              :loading="loading"
              @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 底部信息 -->
      <div class="login-footer">
        <p class="version-info">版本号：v1.0.0</p>
        <p class="copyright">© 2024 收银管理系统 版权所有</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {User, Lock, Key, ShoppingCart} from '@element-plus/icons-vue'
import tool from '@/utils/tool'
import config from '@/config'
import {generateCaptchaDataURL, validateCaptcha} from '@/utils/captcha'
import {mockLoginAPI} from '@/utils/api'
import http from "@/utils/request.js";
import {getLoginSettings} from '@/utils/loginSettings'

const router = useRouter()
const loginFormRef = ref()
const loading = ref(false)
const captchaUrl = ref('')
const currentCaptcha = ref('')

// 登录设置
const loginSettings = ref({
  enableCaptcha: true,
  captchaLength: 4,
  captchaType: 'alphanumeric',
  caseSensitive: false
})

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: '',
  rememberMe: false
})

// 表单验证规则
const loginRules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur'}
  ],
  captcha: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {validator: (rule, value, callback) => {
      if (loginSettings.value.enableCaptcha) {
        if (!value) {
          callback(new Error('请输入验证码'))
        } else if (value.length !== loginSettings.value.captchaLength) {
          callback()
        } else {
          callback()
        }
      } else {
        callback()
      }
    }, trigger: 'blur'}
  ]
}

// 刷新验证码
const refreshCaptcha = () => {
  const captchaData = generateCaptchaDataURL(
    loginSettings.value.captchaLength,
    loginSettings.value.captchaType
  )
  captchaUrl.value = captchaData.dataURL
  currentCaptcha.value = captchaData.code
  console.log(captchaData)
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loading.value = true

    // 验证验证码（如果启用）
    if (loginSettings.value.enableCaptcha) {
      if (!validateCaptcha(loginForm.captcha, currentCaptcha.value, loginSettings.value.caseSensitive)) {
        ElMessage.error('验证码错误')
        refreshCaptcha()
        return
      }
    }

    // 调用登录API
    let res = await http.form('/user/login', loginForm)
    if (res.code !== 200) {
      ElMessage.error(res.data.message)
      return
    }


    // 登录成功处理
    const sessionId =res.data.sessionId;
    tool.data.set('sessionId', sessionId)
    tool.data.set('userInfo', res.data)

    if (loginForm.rememberMe) {
      tool.data.set('rememberedUser', {
        username: loginForm.username,
        rememberMe: true
      })
    } else {
      tool.data.remove('rememberedUser')
    }

    ElMessage.success('登录成功！')
    router.push('/home')

  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error.message || '登录失败，请检查用户名、密码和验证码')
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

// 加载登录设置
const loadLoginSettings = () => {
  try {
    loginSettings.value = getLoginSettings()
  } catch (error) {
    console.error('加载登录设置失败:', error)
  }
}

// 组件挂载时初始化
onMounted(() => {
  // 加载登录设置
  loadLoginSettings()

  // 生成验证码（如果启用）
  if (loginSettings.value.enableCaptcha) {
    refreshCaptcha()
  }

  // 检查是否有记住的用户信息
  const rememberedUser = tool.data.get('rememberedUser')
  if (rememberedUser && rememberedUser.rememberMe) {
    loginForm.username = rememberedUser.username
    loginForm.rememberMe = true
  }
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.bg-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.bg-circle-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.bg-circle-2 {
  width: 150px;
  height: 150px;
  top: 60%;
  right: 15%;
  animation-delay: 2s;
}

.bg-circle-3 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

.login-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 40px;
  width: 400px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 2;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo-container {
  margin-bottom: 16px;
}

.logo-icon {
  color: #409eff;
  background: linear-gradient(135deg, #409eff, #67c23a);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.system-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
  background: linear-gradient(135deg, #409eff, #67c23a);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.system-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
  font-weight: 400;
}

.login-form {
  margin-bottom: 20px;
}

.login-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.login-form :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.login-form :deep(.el-input__wrapper:hover) {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.login-form :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.captcha-container {
  display: flex;
  align-items: center;
}

.captcha-image {
  width: 100px;
  height: 40px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.captcha-image:hover {
  border-color: #409eff;
  transform: scale(1.02);
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.login-btn {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #409eff, #67c23a);
  border: none;
  transition: all 0.3s ease;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(64, 158, 255, 0.3);
}

.login-btn:active {
  transform: translateY(0);
}

.login-footer {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.version-info {
  font-size: 12px;
  color: #909399;
  margin: 0 0 4px 0;
}

.copyright {
  font-size: 12px;
  color: #c0c4cc;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    width: 90%;
    padding: 30px 20px;
  }

  .system-title {
    font-size: 24px;
  }

  .login-btn {
    height: 44px;
    font-size: 15px;
  }
}
</style>
